<!-- 蓝色简洁登录页面 -->
<template>
  <view class="login">
    <div class="content">
      <img class="logo" src="https://aliyundb.mnhes.com/image/default/F6B2D99F6BF8444FA1E1D6C657645AD7-6-2.png" />
      <div class="content-box">
        <div class="content-box-form">
          <u--form :model="form" ref="uForm">
            <u-form-item prop="username">
              <u--input :adjust-position="false" v-model="form.username" placeholder="请输入账号"
                placeholderStyle="color: #fff;font-size:30rpx;" shape="circle" clearable />
            </u-form-item>
            <u-form-item prop="password">
              <u--input :adjust-position="false" v-model="form.password" placeholder="请输入密码" type="password"
                placeholderStyle="color: #fff;font-size:30rpx;" shape="circle" clearable />
            </u-form-item>
            <u-form-item>
              <view class="arithmetic-mverify">
                <canvas style="width: 260rpx; height: 100rpx;" canvas-id="firstCanvas" id="firstCanvas"></canvas>
                <input v-model="arithmetic" class="arithmetic-num" placeholder="请输入结果"
                  placeholder-style='color:#fff;font-size:30rpx;' />
              </view>
            </u-form-item>
          </u--form>
          <view class="agreement">
            <u-checkbox-group>
              <u-checkbox v-model="rem" label="记住密码" labelColor="#fff" labelSize="16px" activeColor="#BA201E"
                inactiveColor="#fff"></u-checkbox>
            </u-checkbox-group>
          </view>
          <u-button shape="circle" @click="submit" :loading="loading" loadingText="登录中...">登录</u-button>
        </div>
      </div>
    </div>
  </view>
</template>
<script>
	import sha256Enc from "crypto-js/sha256.js";
	import {
		ACCESS_TOKEN
	} from '@/store/mutation-types'
	import storage from '@/utils/storage'
	export default {
		data() {
			return {
				form: {
					username: "",
					password: "",
				},
				loginRequest: {
					username: "",
					password: "",
				},
				rem: false,
				rules: {
					username: [{
						required: true,
						message: '请输入账号',
						trigger: ['change', 'blur'],
					}],
					password: [{
						required: true,
						message: '请输入密码',
						trigger: ['change', 'blur'],
					}]
				},
				vertify: false,
				nums: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19],
				result: '',
        arithmetic: "",
        loading: false
			};
		},
		// 必须要在onReady生命周期，因为onLoad生命周期组件可能尚未创建完毕
		onReady() {
			this.$refs.uForm.setRules(this.rules);
		},
		mounted() {
			let _this = this;
			setTimeout(function() {
				_this.init();
			}, 1000)
			this.$nextTick(function() {
				this.initNameAndPwd();
			});
		},
		methods: {
			init() {
				let operators = ['+', '-', '*', '/'];
				let operator = operators[Math.floor(Math.random() * operators.length)];
				let first, second;

				do {
					first = Math.floor(Math.random() * 20);
					second = Math.floor(Math.random() * 20);
				} while (
					(operator === '-' && first < second) ||
					(operator === '/' && (second === 0 || first % second !== 0))
				);

				switch (operator) {
					case '+':
						this.result = first + second;
						break;
					case '-':
						this.result = first - second;
						break;
					case '*':
						this.result = first * second;
						break;
					case '/':
						this.result = first / second;
						break;
				}

				const context = uni.createCanvasContext('firstCanvas');
				context.font = 'italic bold 20px cursive';
				context.setFillStyle("#9acd32");
				context.setFontSize(20);
				context.fillText(first, 0, 30);
				context.setFillStyle("#FEEF3C");
				context.fillText(operator, 30, 30);
				context.setFillStyle("#FB7D23");
				context.rotate(10 * Math.PI / 180);
				context.fillText(second, 50, 30);
				context.setFillStyle("#1e90ff");
				context.rotate(-10 * Math.PI / 180);
				context.fillText("=", 80, 40);
				context.setFontSize(40);
				context.setFillStyle("#50d1bc");
				context.fillText("?", 100, 50);
				context.draw();
			},

      submit () {
				let that = this;
        this.$refs.uForm.validate().then(res => {
          if (!this.arithmetic)
          {
            uni.showToast({
              title: "运算结果不能为空",
              icon: "none",

            });
            return
          }
          if (this.result != this.arithmetic)
          {
            uni.showToast({
              title: "运算结果错误",
              icon: "none",
            });
            this.init()
            this.arithmetic = ''
            return
          }
          that.loginAction();
        }).catch(errors => {
          uni.$u.toast('验证失败')
        })
			},
			loginAction() {
				this.keepNameAndPwd();
				//密码加密
        this.loginSha256PW();
        this.loading = true;
        this.$store.dispatch('Login', this.loginRequest).then(res => {
						if (res.code == 1) {
							uni.showToast({
								title: '登录成功',
								icon: 'success'
							})
							uni.reLaunch({
								url: '/pages/home/index'
              })
              this.loading = false;
						}
					})
					.catch(err => {
            console.log(err, '--err--')
            this.loading = false;
					})
			},
			// sha256进行最初简单加密
			loginSha256ToUper(test) {
				return sha256Enc(test).toString().toUpperCase();
			},
			//密码加密（用户+密码进行Sha256加密）
			loginSha256PW() {
				// 密码加密
				let pwValue1 = this.loginSha256ToUper(this.form.password);
				pwValue1 = this.loginSha256ToUper(
					"CRCLDAP+" + this.form.username + "+" + pwValue1
				);
				this.loginRequest.username = this.form.username;
				this.loginRequest.password = pwValue1;
			},
			keepNameAndPwd() {
				if (this.rem) {
					uni.setStorage({
						key: 'username',
						data: this.form.username
					})
					uni.setStorage({
						key: 'password',
						data: this.form.password
					})
				} else {
					uni.removeStorage({
						key: "username"
					})
					uni.removeStorage({
						key: "password"
					})
				}
			},
			initNameAndPwd() {
				let that = this;
				this.rem = false;
				if (storage.get(ACCESS_TOKEN)) {
					uni.reLaunch({
						url: '/pages/home/index'
					})
				}
			},
		}
	};
</script>
<style lang="scss" scoped>
	@import './index.scss';
</style>